package com.ljq.apipassenger.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ljq.intemalcommon.dto.ResponseResult;
import com.ljq.intemalcommon.dto.TokenResult;
import com.ljq.intemalcommon.util.JwtUtils;
import net.sf.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Configuration
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String resultString = "";

        String token = request.getHeader("Authorization");

        try {
            TokenResult tokenResult = JwtUtils.parseToken(token);
        } catch (SignatureVerificationException e) {
            //签名错误 SignatureVerificationException
            resultString = "token签名错误";
        } catch (TokenExpiredException e) {
            //Token过期 TokenExpiredException
            resultString = "token过期";
        } catch (AlgorithmMismatchException e) {
            //算法异常 AlgorithmMismatchException
            resultString = "token算法异常";
        } catch (Exception e) {
            //token 失效
            resultString = "token无效";
        }
        if (!resultString.equals("")) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            String s = JSON.toJSONString(ResponseResult.fail(resultString));
            printWriter.print(s);
            return false;
        }
        return true;
    }


}
